<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>商家信息</p>
    </header>

    <!-- 商家头部信息 -->
    <div class="business-header">
      <div class="business-header-content">
        <div class="business-logo">
          <img :src="business.businessImg">
        </div>
        <div class="business-info">
          <h1>{{business.businessName}}</h1>
          <div class="rating-line">
            <span class="score">4.5分</span>
            <span>月售1000+</span>
            <span>约32分钟</span>
          </div>
          <div class="delivery-line">
            <span>起送¥{{business.starPrice}}</span>
            <span>配送¥{{business.deliveryPrice}}</span>
            <span>蜂鸟准时达</span>
          </div>
        </div>
      </div>
      <div class="business-tags">
        <span class="business-tag">食无忧</span>
        <span class="business-tag">外卖保</span>
      </div>
    </div>

    <!-- 导航栏 -->
    <div class="nav-bar">
      <div class="nav-item active">点餐</div>
      <div class="nav-item">评价</div>
      <div class="nav-item">商家</div>
    </div>

    <!-- 食品列表部分 -->
    <ul class="food">
      <li v-for="(item,index) in foodArr">
        <div class="food-left">
          <img :src="item.foodImg">
          <div class="food-left-info">
            <h3>{{item.foodName}}</h3>
            <p>{{item.foodExplain}}</p>
            <p>&#165;{{item.foodPrice}}</p>
          </div>
        </div>
        <div class="food-right">
          <div>
            <i class="fa fa-minus-circle" @click="minus(index)" v-show="item.quantity!=0"></i>
          </div>
          <p><span v-show="item.quantity!=0">{{item.quantity}}</span></p>
          <div>
            <i class="fa fa-plus-circle" @click="add(index)"></i>
          </div>
        </div>
      </li>
    </ul>

    <!-- 购物车部分 -->
    <div class="cart">
      <div class="cart-left">
        <div class="cart-left-icon" :style="totalQuantity==0?'background-color:#505051;':'background-color:#3190E8;'">
          <i class="fa fa-shopping-cart"></i>
          <div class="cart-left-icon-quantity" v-show="totalQuantity!=0">{{totalQuantity}}</div>
        </div>
        <div class="cart-left-info">
          <p>&#165;{{totalPrice}}</p>
          <p>另需配送费{{business.deliveryPrice}}元</p>
        </div>
      </div>
      <div class="cart-right">
        <div class="cart-right-item" v-show="totalSettle<business.starPrice" style="background-color: #535356;cursor: default;">
          &#165;{{business.starPrice}}起送
        </div>
        <div class="cart-right-item" @click="toOrder" v-show="totalSettle>=business.starPrice">
          去结算
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getCurrentInstance } from 'vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import qs from 'qs'

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()

const businessId = ref(route.query.businessId)
const business = ref({})
const foodArr = ref([])
const user = ref({})

onMounted(() => {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  user.value = proxy.$getSessionStorage('user')
  if (!user.value) {
    ElMessage.warning('用户信息已失效，请重新登录')
    router.push('/login')
    return
  }
  
  // 根据businessId查询商家信息
  request({
    url: '/BusinessController/getBusinessById',
    method: 'get',
    params: {
      businessId: businessId.value
    }
  }).then(response => {
    business.value = response.data
  }).catch(error => {
    console.error(error)
    if (error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      proxy.$removeSessionStorage('user')
      router.push('/login')
    } else {
      ElMessage.error('获取商家信息失败')
    }
  })

  // 根据businessId查询所属食品信息
  request({
    url: '/FoodController/listFoodByBusinessId',
    method: 'get',
    params: {
      businessId: businessId.value
    }
  }).then(response => {
    foodArr.value = response.data
    for (let i = 0; i < foodArr.value.length; i++) {
      foodArr.value[i].quantity = 0
    }

    // 如果已登录，那么需要去查询购物车中是否已经选购了某个食品
    listCart()
  }).catch(error => {
    console.error(error)
    if (error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      proxy.$removeSessionStorage('user')
      router.push('/login')
    } else {
      ElMessage.error('获取食品列表失败')
    }
  })
})

const listCart = () => {
  request({
    url: '/CartController/listCart',
    method: 'get',
    params: {
      businessId: businessId.value,
      userId: user.value.userId
    }
  }).then(response => {
    let cartArr = response.data
    // 遍历所有食品列表
    for (let foodItem of foodArr.value) {
      for (let cartItem of cartArr) {
        if (cartItem.foodId === foodItem.foodId) {
          foodItem.quantity = cartItem.quantity
          break
        }
      }
    }
  }).catch(error => {
    console.error(error)
    if (error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      proxy.$removeSessionStorage('user')
      router.push('/login')
    } else {
      ElMessage.error('获取购物车信息失败')
    }
  })
}

const add = (index) => {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  if (!user.value) {
    ElMessage.warning('用户信息已失效，请重新登录')
    router.push('/login')
    return
  }

  if (foodArr.value[index].quantity === 0) {
    saveCart(index)
  } else {
    updateCart(index, 1)
  }
}

const minus = (index) => {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  if (!user.value) {
    ElMessage.warning('用户信息已失效，请重新登录')
    router.push('/login')
    return
  }

  if (foodArr.value[index].quantity > 1) {
    updateCart(index, -1)
  } else if (foodArr.value[index].quantity === 1) {
    removeCart(index)
  }
}

const saveCart = (index) => {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  request({
    url: '/CartController/saveCart',
    method: 'post',
    headers: {
      'Authorization': token,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: qs.stringify({
      businessId: businessId.value,
      userId: user.value.userId,
      foodId: foodArr.value[index].foodId
    })
  }).then(response => {
    if (response.data === 1) {
      foodArr.value[index].quantity = 1
      ElMessage.success('添加成功')
    } else {
      ElMessage.error('添加失败')
    }
  }).catch(error => {
    console.error('保存购物车错误:', error.response || error)
    if (error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      proxy.$removeSessionStorage('user')
      router.push('/login')
    } else {
      ElMessage.error('添加失败')
    }
  })
}

const updateCart = (index, num) => {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  const newQuantity = foodArr.value[index].quantity + num
  if (newQuantity < 0) {
    ElMessage.warning('数量不能小于0')
    return
  }

  request({
    url: '/CartController/updateCart',
    method: 'put',
    headers: {
      'Authorization': token,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: qs.stringify({
      businessId: businessId.value,
      userId: user.value.userId,
      foodId: foodArr.value[index].foodId,
      quantity: newQuantity
    })
  }).then(response => {
    if (response.data === 1) {
      foodArr.value[index].quantity = newQuantity
      ElMessage.success(num > 0 ? '添加成功' : '减少成功')
    } else {
      ElMessage.error('更新失败')
    }
  }).catch(error => {
    console.error('更新购物车错误:', error.response || error)
    if (error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      proxy.$removeSessionStorage('user')
      router.push('/login')
    } else {
      ElMessage.error('更新失败')
    }
  })
}

const removeCart = (index) => {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  request({
    url: '/CartController/removeCart',
    method: 'delete',
    headers: {
      'Authorization': token,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: qs.stringify({
      businessId: businessId.value,
      userId: user.value.userId,
      foodId: foodArr.value[index].foodId
    })
  }).then(response => {
    if (response.data === 1) {
      foodArr.value[index].quantity = 0
      ElMessage.success('移除成功')
    } else {
      ElMessage.error('移除失败')
    }
  }).catch(error => {
    console.error('移除购物车错误:', error.response || error)
    if (error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      proxy.$removeSessionStorage('user')
      router.push('/login')
    } else {
      ElMessage.error('移除失败')
    }
  })
}

const toOrder = () => {
  if (!user.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  if (totalQuantity.value === 0) {
    ElMessage.warning('请先选择商品')
    return
  }

  if (totalSettle.value < business.value.starPrice) {
    ElMessage.warning(`还差${(business.value.starPrice - totalSettle.value).toFixed(2)}元起送`)
    return
  }

  router.push({
    path: '/orders',
    query: { businessId: businessId.value }
  })
}

// 计算属性
const totalPrice = computed(() => {
  let total = 0
  for (let item of foodArr.value) {
    total += (item.foodPrice * (item.quantity || 0))
  }
  return total.toFixed(2)
})

const totalQuantity = computed(() => {
  let total = 0
  for (let item of foodArr.value) {
    total += item.quantity || 0
  }
  return total
})

const totalSettle = computed(() => {
  return Number(totalPrice.value) + (business.value.deliveryPrice || 0)
})
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}
/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 44px;
  background-color: #0097FF;
  color: #fff;
  font-size: 16px;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}
/****************** 商家头部信息 */
.business-header {
  background: #333;
  color: #fff;
  padding: 15px 12px;
  margin-top: 44px;
}
.business-header-content {
  display: flex;
  align-items: center;
  gap: 12px;
}
.business-logo {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
}
.business-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.business-info {
  flex: 1;
}
.business-info h1 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}
.business-info .rating-line {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #fff;
  margin-bottom: 6px;
}
.business-info .rating-line .score {
  color: #ff6b01;
}
.business-info .delivery-line {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}
.business-tags {
  margin-top: 12px;
  display: flex;
  gap: 8px;
}
.business-tag {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  padding: 2px 6px;
  border-radius: 2px;
  font-size: 12px;
}
/****************** 导航栏 ******************/
.nav-bar {
  display: flex;
  background: #fff;
  border-bottom: 1px solid #eee;
}
.nav-item {
  flex: 1;
  padding: 12px 0;
  text-align: center;
  font-size: 14px;
  color: #666;
  position: relative;
}
.nav-item.active {
  color: #333;
  font-weight: bold;
}
.nav-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 2px;
  background: #0097FF;
}
/****************** 食品列表部分 ******************/
.wrapper .food {
  background: #fff;
  padding: 0;
  margin-bottom: 50px;
}
.wrapper .food li {
  display: flex;
  padding: 15px 12px;
  border-bottom: 1px solid #f5f5f5;
}
.wrapper .food li .food-left {
  flex: 1;
  display: flex;
  gap: 12px;
}
.wrapper .food li .food-left img {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
}
.wrapper .food li .food-left .food-left-info {
  flex: 1;
}
.wrapper .food li .food-left .food-left-info h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 6px;
}
.wrapper .food li .food-left .food-left-info p:first-of-type {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}
.wrapper .food li .food-left .food-left-info p:last-of-type {
  font-size: 16px;
  color: #ff4e00;
  font-weight: bold;
}
.wrapper .food li .food-right {
  display: flex;
  align-items: center;
  gap: 8px;
}
.wrapper .food li .food-right .fa-minus-circle {
  font-size: 24px;
  color: #0097FF;
  cursor: pointer;
}
.wrapper .food li .food-right p {
  font-size: 16px;
  color: #333;
  min-width: 24px;
  text-align: center;
}
.wrapper .food li .food-right .fa-plus-circle {
  font-size: 24px;
  color: #0097FF;
  cursor: pointer;
}
/****************** 购物车部分 ******************/
.wrapper .cart {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 50px;
  background: #333;
  display: flex;
}
.wrapper .cart .cart-left {
  flex: 2;
  display: flex;
  align-items: center;
  padding: 0 12px;
  gap: 12px;
}
.wrapper .cart .cart-left .cart-left-icon {
  width: 45px;
  height: 45px;
  background: #0097FF;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: -10px;
  position: relative;
}
.wrapper .cart .cart-left .cart-left-icon .fa-shopping-cart {
  font-size: 20px;
  color: #fff;
}
.wrapper .cart .cart-left .cart-left-icon-quantity {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #ff4e00;
  color: #fff;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 8px;
  min-width: 16px;
  text-align: center;
}
.wrapper .cart .cart-left .cart-left-info {
  color: #fff;
}
.wrapper .cart .cart-left .cart-left-info p:first-child {
  font-size: 18px;
  font-weight: bold;
}
.wrapper .cart .cart-left .cart-left-info p:last-child {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}
.wrapper .cart .cart-right {
  flex: 1;
}
.wrapper .cart .cart-right .cart-right-item {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
  background: #38CA73;
  cursor: pointer;
}
.wrapper .cart .cart-right .cart-right-item.disabled {
  background: #666;
  cursor: not-allowed;
}
</style>